package com.example.application4.activity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;

import com.example.application4.R;
import com.example.application4.pojo.Diary;
import com.example.application4.util.SharedPreferencesManager;

import java.util.List;

public class DiaryViewActivity extends AppCompatActivity {
    private String username;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.diary_view);

        // 获取当前用户的名称
        SharedPreferences preferences = getSharedPreferences("appPreferences", MODE_PRIVATE);
        username = preferences.getString("username", "");

        if (username.isEmpty()) {
            showToast("用户未登录或用户名称无效");
            finish();
            return;
        }

        // 获取传递过来的日记 ID
        Integer id = getIntent().getIntExtra("id", -1);
        if (id == -1) {
            showToast("无效的日记ID");
            finish();
            return;
        }

        // 根据 ID 查找日记
        Diary diary = findDiaryById(id);
        if (diary == null) {
            // 如果未找到日记，处理错误情况
            showToast("未找到日记");
            finish();
            return;
        }

        // 显示日记内容
        displayDiary(diary);
        // 设置关闭按钮
        setupCloseButton();
    }

    private Diary findDiaryById(Integer id) {
        // 从 SharedPreferences 中获取当前用户的日记条目
        List<Diary> diaryEntries = SharedPreferencesManager.getDiaryEntries(this, username);
        for (Diary d : diaryEntries) {
            if (id.equals(d.getId())) {
                return d;
            }
        }
        return null;
    }

    private void displayDiary(Diary diary) {
        // 设置日记的标题、内容和创建日期
        ((TextView) findViewById(R.id.title_input)).setText(diary.getTitle());
        ((TextView) findViewById(R.id.content_input)).setText(diary.getContent());
        ((TextView) findViewById(R.id.createDate)).setText(diary.getDate());

        // 设置 TextView 不可编辑
        setTextViewFocusable(R.id.title_input);
        setTextViewFocusable(R.id.createDate);
        setTextViewFocusable(R.id.content_input);
    }

    private void setTextViewFocusable(int textViewId) {
        // 获取指定 ID 的 TextView 并设置其不可编辑
        TextView textView = findViewById(textViewId);
        textView.setFocusable(false);
        textView.setClickable(false);
        textView.setLongClickable(false);
    }

    private void setupCloseButton() {
        Button closeButton = findViewById(R.id.return_button);
        closeButton.setOnClickListener(view -> finish());
    }

    private void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }
}